#include "myserver.h"

myserver::myserver():server()
{
    this->val = 0;
    this->step = 0;
    this->l = NULL;
    this->id = 0;
	this->allanswer = NULL;
	this->stt = 0;

}
myserver::~myserver()
{
    this->val = 0;
    this->step = 0;
    this->l = NULL;
    this->id = 0;
	this->allanswer = NULL;
	this->stt = 0;

}
void myserver::myservermakevaluegame()
{
    srand((unsigned int)time(NULL));
    for(int i=0; i<50; i++)
    {
        let[i].setall(i+1,0);
    }
    //tao bao thu 10.000.000->value = 10000
    int num = 0;
    int vl;
    while(num < 2)
    {
again1:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again1;
        }
        else
        {
            let[vl].setvalue(10000);
            num++;
        }
    }
    num = 0;
    while(num < 2)
    {
again2:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again2;
        }
        else
        {
            let[vl].setvalue(5000);
            num++;
        }
    }
    num = 0;
    while(num < 4)
    {
again3:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again3;
        }
        else
        {
            let[vl].setvalue(1000);
            num++;
        }
    }
    num = 0;
    while(num < 4)
    {
again4:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again4;
        }
        else
        {
            let[vl].setvalue(500);
            num++;
        }
    }
    num = 0;
    while(num < 4)
    {
again5:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again5;
        }
        else
        {
            let[vl].setvalue(100);
            num++;
        }
    }
    num = 0;
    while(num < 4)
    {
again6:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again6;
        }
        else
        {
            let[vl].setvalue(50);
            num++;
        }
    }
    num = 0;
    while(num < 2)
    {
again7:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again7;
        }
        else
        {
            let[vl].setvalue(-100);
            num++;
        }
    }
    num = 0;
    while(num < 4)
    {
again8:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again8;
        }
        else
        {
            let[vl].setvalue(-50);
            num++;
        }
    }
    num = 0;
    while(num < 4)
    {
again9:
        vl = rand()%50;
        if(let[vl].getvalue() != 0)
        {
            goto again9;
        }
        else
        {
            let[vl].setvalue(-25);
            num++;
        }
    }
}
void myserver::myserverintro()
{
    cout<<"============================= LAP TRINH SOCKET======================="<<endl;
    cout<<"Ho ten             : Pham Van Diep "<<endl;
    cout<<"Mssv               : 0967023 "<<endl;
    cout<<"Ngon ngu           : c++ "<<endl;
    cout<<"Ten chuong trinh   : Tro choi dau tri "<<endl;
    cout<<"Port               : 9999 " <<endl;
    cout<<"------------------------------------------------------------  "<<endl;
    cout<<"Luat choi   :  "<<endl;
    cout<<"Server khoi tao 50 bao thu  "<<endl;
    cout<<"Voi cac gia tri : 10.000.000 <-> 2 ,5.000.000 <-> 2 "<<endl;
    cout<<"                  1.000.000  <-> 4 ,500.000   <-> 4 "<<endl;
    cout<<"                  100.000    <-> 4 ,50.000    <-> 4  "<<endl;
    cout<<"                  -100%      <-> 2 ,-50%      <-> 4 "<<endl;
    cout<<"                  -25%       <-> 4   "<<endl;
    cout<<"Nguoi choi o server nhap luong bao thu ma client duoc mo <1-5> "<<endl;
    cout<<"Khoi tao ngan phieu cua client :0 dong ,cho client connect  "<<endl;
    cout<<"Server gui so luong bao thu duoc mo cho client "<<endl;
    cout<<"Server cho nhan client chon bao thu muon mo "<<endl;
    cout<<"Server nhap cau hoi,cau tra loi gui cho client "<<endl;
    cout<<"Server cho nhan cau tra loi ,dung thi bao thu cua client "<<endl;
    cout<<"Khi da mo het so bao thu ma server cho phep client mo "<<endl;
    cout<<"Neu so bao thu client co < 0 ,tro choi ket thuc "<<endl;
    cout<<"Nguoc lai Server chon mua 1 bao thu,hoac 1 bao thu va ngan phieu,hoac 2 bao thu "<<endl;
    cout<<"Voi gia ma server muon mua,neu client dong y thi cap nhat bao thu cua client va ngan phieu "<<endl;
    cout<<"Neu khong client gui gia muon ban "<<endl;
    cout<<"Neu client client muon ket thuc chuong trinh ,client gui tin hieu ve server "<<endl;
    cout<<"Neu muon choi tiep ,tro choi quay lai tu dau "<<endl;
    cout<<" ------------------------------------------------------------ "<<endl;
}
void myserver::myserverstart()
{
    myserverintro();
    if(serverinit() == 1)
    {
        cout<<"Init successful ."<<endl;
        if(servercreatesocket() == 1)
        {
            cout<<"Create socket succesful ."<<endl;
            if(serverbind() == 1)
            {
                cout<<"Bind successful ."<<endl;
                if(serverlisten() == 1)
                {
                    cout<<"Server listenning ... "<<endl;
                    if(serveraccept() == 1)
                    {
                        cout<<"Client connected ."<<endl;
                        while(1)
                        {
                            myservermakevaluegame();
                            myserverprocessgame();
                            myserverprocessfinish();

                        }
                    }
                    else
                    {
                        serverclose();
                        cout<<"Accept failed ."<<endl;
                        cin.get();
                        cin.get();
                        exit(-5);
                    }
                }
                else
                {
                    serversocketclose();
                    cout<<"Listen failed ."<<endl;
                    cin.get();
                    cin.get();
                    exit(-4);
                }
            }
            else
            {
                servercleanup();
                cout<<"Bind failed."<<endl;
                cin.get();
                cin.get();
                exit(-3);
            }
        }
        else
        {
            servercleanup();
            cout<<"Create socket failed."<<endl;
            cin.get();
            cin.get();
            exit(-2);
        }

    }
    else
    {
        servercleanup();
        cout<<"Winsock init failed  ."<<endl;
        cin.get();
        cin.get();
        exit(-1);
    }

}
void myserver::myserverprocessgame()
{
	int st = 0,letterid,answertrue;
    myservergetparameters();
	myserversendstep();
    while(st < step)
    {
		system("cls");
		cout<<"Client duoc mo : "<<step<<" bao thu ."<<endl;
		cout<<"\t\t\t\t\t Luot thu :"<<st+1<<endl;
		myserverprintletter();
		letterid = myservergetletterid(st);
		answertrue = myservermakequestion();
        //kiem tra tra loi dung hay sai
		myserversendclientresult(letterid,answertrue);
        //xuat bao thu client hien co
        st++;


    }

}
void myserver::myserversendclientresult(int letterid,int answertrue)
{
		cout<<"Dang cho client ... "<<endl;
		serverrecv();
		if(myservercheckresult(letterid,answertrue) == 1)
        {
            sen.datasetvalue(6,1,"","","","","",l[id-1]);
        }
        else
        {
            sen.datasetvalue(6,0,"","","","","",-1);
        }
        //cho biet tra loi dung hay sai 1:dung 0 :sai
        serversend();
}
int myserver::myservermakequestion()
{
	 string ques,an1,an2,an3,an4;
	 int antrue;
		cin.ignore(2000,'\n');
        cout<<"Cau hoi: "<<endl;cout<<"--------"<<endl;
        getline(cin,ques,'\n');
        cout<<endl;
        cout<<"Dap an 1 : "<<endl;cout<<"---------"<<endl;
        getline(cin,an1,'\n');
        cout<<endl;
        cout<<"Dap an 2 : "<<endl;cout<<"---------"<<endl;
        getline(cin,an2,'\n');
        cout<<endl;
        cout<<"Dap an 3 : "<<endl;cout<<"---------"<<endl;
        getline(cin,an3,'\n');
        cout<<endl;
        cout<<"Dap an 4 : "<<endl;cout<<"---------"<<endl;
        getline(cin,an4,'\n');
        cout<<endl;
        do
        {
				cout<<"Dap an dung <1-4> : "<<endl;cout<<"-------------------"<<endl;
				cin>>antrue;
				if(cin.fail())
				{
					cin.clear();
					cin.ignore(2000,'\n');
					cout<<"Ban can nhap so tu 1->4 : "<<endl;
					cin>>antrue;
			
				}
				cout<<endl;	
        }while(antrue <1 || antrue > 4 );

        sen.datasetvalue(3,-1,ques,an1,an2,an3,an4,-1);
        serversend();
		return antrue;
        
}
int myserver::myservergetletterid(int st)
{
	
	 
		sen.datasetvalue(2,-1,"","","","","",st+1);
again:
		serversend();
		cout<<"Dang cho client ... "<<endl;
        serverrecv();
        int re = rec.datagetx();
		//do client nhap 1-50,server 0-49
		re = re - 1;
		cout<<"Bao thu client da chon : "<<re<<endl;
		//kiem tra id nay hop le k?
        while(myservercheckid(re) == -1)
        {
            sen.datasetvalue(-3,-1,"","","","","",-1);
            goto again;
        }
		return re;

}
void myserver::myserversendstep()
{
	sen.datasetvalue(1,step,"","","","","",-1);
     serversend();
}
int myserver::myservercheckid(int idd)
{
    if(idd < 0 || idd > 49)
    {
        return -1;
    }

    else
    {

        for(int i = 0; i< stt; i++)
        {
            if(allanswer[i] == idd)
            {
                return -1;
            }
        }
		allanswer[stt++] = idd;
        return 1;
    }
}
void myserver::myserverprintletter()
{
		
        cout<<"\t\t\t\t\tNgan luong cua client : "<<val*1000<<" dong."<<endl;;
		cout<<"\t\t\t\t\tBao thu client da chon ";
        for(int i = 0 ;i < stt ;i++)
        {
            cout<<" : "<<allanswer[i];
        }
        cout<<endl;
        cout<<"\t\t\t\t\tID Bao thu client hien co  ";
        for(int i = 0 ;i < id ;i++)
        {
            cout<<" : "<<l[i];
        }
        cout<<endl;
		cout<<" ---------------------------------------------------------------"<<endl;
}
int myserver::myservercheckresult(int idd,int anstrue)
{
	//cho na con van de
    int result = rec.datagetx();
        if(result == anstrue)
        {
			cout<<"Client da tra loi dung ."<<endl;
                l[id++] = let[idd].getid();
                return 1;

        }
        else
        {
			cout<<"Client tra loi sai ."<<endl;
            return -1;
        }

}
void myserver::myservergetparameters()
{
    
	id = 0;
    l = NULL;
	stt = 0;
	allanswer = NULL;
   // this->val = 0;
    this->step = 0;
   do
    {
			cout<<"So bao thu client duoc mo <1-5>:";
			cin>>this->step;
			if(cin.fail())
			{
				cin.clear();
				cin.ignore(2000,'\n');
				cout<<"Ban can nhap so tu 1->5 : ";
				cin>>this->step;
			
			}
			cout<<endl;
    }while(step < 1 || step > 5 );
    l = new int[step];
	allanswer = new int[step];
    for(int i=0 ; i<step; i++)
    {
        l[i] = 0;
		allanswer[i] = 0;
    }
}
int myserver::myservercountelement(int *arr,int size)
{
	int num = 0;
	for(int i=0;i<size;i++)
	{
		if(arr[i] >0 )
		{
			num++;
		}
	}
	return num;
}
void myserver::myserverprocessfinish()
{
    int num_element;
    //sai cho nay
    //khong co bao thu van gui mua
	num_element = myservercountelement(l,id);
    if(num_element > 0)
    {
        myserverbuy();
		myserverprintletter();
		myservercalculatelettervalue();
		myserveraskexityesorno();

    }
    else
    {
        //thoat chuong trinh
        cout<<"Game ket thuc ."<<endl;
		cout<<"\t\t\t\t\tNgan luong cua client : "<<val*1000<<" dong."<<endl;
        sen.datasetvalue(0,-1,"","","","","",-1);
        serversend();
        serverclose();
        cin.get();
        cin.get();
        exit(0);
    }

}
void myserver::myserverbuy()
{
		int choo,num_element;
		num_element = myservercountelement(l,id);
		if(num_element == 1)
        {
            //chi co 1 bao thu
            choo = 1;
        }
        else
        {
            //du ca
again:choo = rand()%3+1;
			if(val == 0 && choo == 2)
			{
				goto again;
			}
        }
        int price;
        switch(choo)
        {
        case 1:
            price = rand()%1000+1;
            sen.datasetvalue(4,choo,"","","","","",price);
            break;
        case 2:
            price = rand()%5000;
            sen.datasetvalue(4,choo,"","","","","",price);
            break;
        case 3:
            price = rand()%1000 + val;
            sen.datasetvalue(4,choo,"","","","","",price);
            break;
        }
        //gui gia muon mua
        serversend();
        //nhan tra loi
		cout<<"Dang cho client ... "<<endl;
        serverrecv();
        int yesno = rec.datagetx();
        if(yesno == 1)
        {
            cout<<"Client dong y ban voi gia : "<<price<<endl;;
			val =+ price;
			myserverupdateletter(choo);
			sen.datasetvalue(5,val,"","","","","",-1);
			serversend();

        }
        else
        {
			int clientval;
            clientval = rec.datagetansertrue();
			//neu gia cua client dua gia lon hon 10% gia so ver muon mua 
			//server se khong mua
			if(clientval > price*1.1)
			{
				cout<<"Gia dua ra qua cao . Khong the mua ."<<endl;
				sen.datasetvalue(8,0,"","","","","",-1);
				serversend();
			}
			else
			{
				cout<<"Dong y mua cua client voi gia : "<<clientval<<endl;
				val += clientval;
				myserverupdateletter(choo);
				sen.datasetvalue(5,val,"","","","","",-1);
				 serversend();
			}

        }  
        //gui cap nhat gia ti cua client
        
}
void myserver::myserverupdateletter(int choo)
{
	switch(choo)
	{
	case 1:
		id--;
          sen.datasetvalue(7,-1,"","","","","",id);
		  break;

	case 2:
		id--;
          sen.datasetvalue(7,id--,"","","","","",id);
		  break;
	case 3:
		id--;
        sen.datasetvalue(7,-1,"","","","","",id);
		break;

	}
	serversend();
	
}
void myserver::myserveraskexityesorno()
{
	sen.datasetvalue(9,-1,"","","","","",-1);
	serversend();
	cout<<"Dang cho client ... "<<endl;
	serverrecv();
     if(rec.datagettype() == 0)
     {
            //ket thuc;
            cout<<"Client muon ket thuc game ."<<endl;
			myserverprintletter();
            sen.datasetvalue(0,-1,"","","","","",-1);
            serversend();
            serverclose();
            cin.get();
            cin.get();
            exit(0);
       }
	 else
	 {
		 cout<<"Client muon tiep tuc choi ."<<endl;
	 }
}
void myserver::myservercalculatelettervalue()
{
	int num_element = myservercountelement(l,id);
        if(num_element > 0)
        {
            for(int t=0; t<id; t++)
            {
				cout<<"Dang mo bao thu : "<<l[t]<<endl;
                int yourval =  let[l[t]].getvalue();
				cout<<"Gia tri cua bao thu : ";
                if(yourval > 0)
                {
					cout<<yourval*1000<<" dong "<<endl;
                    val = val + yourval;
                }
                else
                {
                    if(yourval == -100)
                    {
						cout<<yourval<<"%"<<endl;
                        val = 0;
                    }
                    else if(yourval == -50)
                    {
						cout<<yourval<<"%"<<endl;
                        val = val/2;
                    }
					else if(yourval == -25)
					{
						cout<<yourval<<"%"<<endl;
						val = val/4;
					}
                    else
                    {
						cout<<yourval<<endl;
                        
                    }

                }
				//gui cap nhat bao thu
				sen.datasetvalue(7,-1,"","","","","",1);
				serversend();
				//gui gia ti bao thu dc mo
				sen.datasetvalue(10,yourval,"","","","","",1);
				serversend();
            }
			
         id = -1;

        }
        
}
